package org.jeecg;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {

	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT="C:\\Users\\Administrator\\Desktop\\web";
	
	/**
	 * 初始化
	 * @param socket
	 */
	public Processor(Socket socket){
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("--> error - 获取 socket 流失败...");
			e.printStackTrace();
		}
	}
	
	public void run (){
		String fileName = parse(in);
		sendFile(fileName);
	}
	
	/**
	 * 取得访问信息
	 * @param in
	 * @return
	 */
	public String parse(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httmMessage = br.readLine();
			String[] content = httmMessage.split(" ");
			
			if(content.length != 3){
				sendErrorMessage(400, "请求失败.");
				System.out.println("--> error - 400请求失败...");
			}else{
				fileName = content[1];
				if("/".equals(fileName)){
					fileName = fileName + "index.html";
				}
				System.out.println("状态:" + content[0] + ",名称:" + content[1] + ",http版本号:" + content[2]);
			}
		} catch (IOException e) {
			System.out.println("--> error - 取得文件名称失败...");
			e.printStackTrace();
		}
		return fileName;
	}
	
	/**
	 * 响应对应的错误页面
	 * @param errorCode
	 * @param errorMessage
	 */
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("HTTP/1.0" + " " + errorCode + " " + "error");
		out.println("content-type: text/html;charset=UTF-8");
		out.println();
		out.println("<html>");
		out.println("<title>Error Page</title>");
		out.println("<body>");
		out.println("<h3>errorCode:" + errorCode + ",errorMessage:" + errorMessage + "</h3>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	/**
	 * 响应相应的访问资源
	 * @param fileName 资源名称
	 */
	public void sendFile(String fileName){
		File file = new File( WEB_ROOT + fileName);
		if(!file.exists()){
			sendErrorMessage(404,"文件不存在!");
			System.out.println("--> error - 404文件不存在...");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte[] content = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 success");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("--> error - 读取文件失败...");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("--> error - 读取文件失败...");
			e.printStackTrace();
		}
	}
}
